package com.lxz.rabbitmq.simple;


import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @date: 2021-06-03 14:57
 * @author: liangxz
 */
//简单模式
public class Consumer {

    public static void main(String[] args){

        //所有的中间件技术都是基于tcp/ip协议基础之上构建新型的的协议规范，只不过rabbitmq遵循的是AMQP协议

        //1.创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");  //设置虚拟节点，也就是放在rabbitmq的根目录下

        Connection connection = null;
        Channel channel=null;
        try {
            //2、创建连接connection
            connection = connectionFactory.newConnection("");
            //3、通过连接获取通道channel
            channel = connection.createChannel();

            //接收消息
            channel.basicConsume("queue1", true, new DeliverCallback() {
                public void handle(String consumerTag, Delivery message) throws IOException {
                    System.out.println("收到消息是" + new String(message.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {   //失败的回调函数
                public void handle(String consumerTag) throws IOException {
                    System.out.println("接收失败了......");
                }
            });
            System.out.println("开始接收消息");
            System.in.read(); //阻断，程序不往下执行，开始接收消息先

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //7、关闭通道
            if (channel!=null && channel.isOpen()){
                try {
                    channel.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            //8、关闭连接
            if (connection!=null && connection.isOpen()){
                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

    }}